<template>
  <a-card :bordered="false">
    <van-search placeholder="请选择条件查询" readonly @click="showSearchPopup" style="margin-top: -10px;width: 100%;padding: 0px;margin-bottom: 10px"/>
    <a-button type="primary" @click="searchReset" icon="reload" style="width: 100%;margin-bottom: 10px">重置</a-button>
    <!-- 查询区域 -->
    <!--<div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-model-item label="单据时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplier">
              <a-checkable-tag style="font-size: 14px;margin:0 5px;padding: 5px" v-for="(item,index) in this.receiptsDateList"
                               :key="index" v-model:checked="item.checkedValue"
                               @change="onChangeReceiptsDate(item.key,item.itemValue)">{{item.itemText}}
              </a-checkable-tag>
              <a-range-picker v-show="this.currentKey1" @change="onChangeCustomerReceiptsDate" format="YYYY-MM-DD"
                              v-model:value="dateValue1"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-model-item label="结案时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplier">
              <a-checkable-tag style="font-size: 14px;margin:0 5px;padding: 5px" v-for="(item,index) in this.closeCaseDateList"
                               :key="index" v-model:checked="item.checkedValue"
                               @change="onChangeCloseCaseDate(item.key,item.itemValue)">{{item.itemText}}
              </a-checkable-tag>
              <a-range-picker v-show="this.currentKey2" @change="onChangeCustomerCloseCaseDate" format="YYYY-MM-DD"
                              v-model:value="dateValue2"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="5">
            <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplier">
              <a-select
                show-search
                :allowClear="true"
                placeholder="请选择供应商"
                option-filter-prop="children"
                v-model="queryParam.supplierName"
                style="width: 100%"
                :filter-option="filterOptionSupplier"
                @change="changeSupplier">
                <a-select-option :value="item.supplierName" v-for="(item,index) in supplierData" :key="index">
                  {{item.supplierName}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-model-item label="采购人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplier">
              <a-select
                show-search
                :allowClear="true"
                placeholder="请选择采购人员"
                option-filter-prop="children"
                v-model="queryParam.purchasePeople"
                style="width: 100%"
                :filter-option="filterOptionPurchasePeople"
                @change="changePurchasePeople">
                <a-select-option :value="item.realname" v-for="(item,index) in purchasePeopleData" :key="index">
                  {{item.realname}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-model-item label="结案状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplier">
              <a-select
                :allowClear="true"
                placeholder="请选择结案状态"
                v-model="queryParam.closeCaseStatus"
                style="width: 100%"
                @change="changeCloseCaseStatus">
                <a-select-option value="1">
                  未结案
                </a-select-option>
                <a-select-option value="2">
                  已结案
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="添加人">
              <a-tree-select
                style="width: 50%"
                :allowClear="true"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="departListData"
                :replaceFields="dataFields"
                placeholder="请选择部门"
                @change="changeDepart"
              >
              </a-tree-select>
              <span style="margin-left: 1%;margin-right: 1%">&#45;&#45;</span>
              <a-select
                show-search
                :allowClear="true"
                placeholder="请选择创建人"
                option-filter-prop="children"
                v-model="queryParam.createBy"
                style="width: 30%;"
                :filter-option="filterOptionCreateBy"
                @change="changeCreateBy">
                <a-select-option :value="item.realname" v-for="(item,index) in createByData" :key="index">
                  {{item.realname}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form>
    </div>-->
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <!--<div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls('供应链采购订单表')">导出</a-button>

    </div>-->

    <!-- table区域-begin -->
    <div>
      <!--<div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
        selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>-->

      <div class="list">
        <van-list
          v-model="loading"
          :finished="finished"
          offset="100"
          finished-text="没有更多了"
          @load="onLoadList"
          :immediate-check="false"
        >
          <div
            class="customer-list"
            v-for="(item,i) in dataSource"
            :key="i"
            @click="inDepositoryOrderDetail(item)"
          >
            <div>
              <div class="name">订单编号：{{ item.purchaseNo || '无' }}</div>
              <div class="contact">
                <span>单据日期：{{ item.createTime || '无' }}</span>
              </div>
              <div class="contact">
                <span>供应商：{{ item.supplierName || '无' }}</span>
              </div>
              <div class="contact">
                <span>采购人员：{{item.purchasePeople || '无'}}</span>
                <span style="margin-left: 20px">创建人：{{ item.createBy || '无' }}</span>
                <span style="float: right">
                  <a @click.stop="payment(item)" v-if="item.payStatus == 1 && item.amountToBePaid != 0 && item.closeCaseStatus == 1">付款</a>
                  <a-divider type="vertical" v-if="item.payStatus == 1 && item.amountToBePaid != 0 && item.closeCaseStatus == 1"/>
                  <a @click.stop="closeCase(item)" v-if="item.closeCaseStatus == 1">结案</a>
                  <a @click.stop="noCloseCase(item)" v-if="item.closeCaseStatus == 2">反结案</a>
                </span>
              </div>
              <div class="contact">
                <span>仓库：{{ item.depositoryName || '无' }}</span>
              </div>
              <div class="contact">
                <span>应付金额：{{ item.sumPayable || 0 }}</span>
                <span style="margin-left: 20px;margin-right: 20px">已付金额：{{ item.amountPaid || 0 }}</span>
                <span>待付金额：{{ item.amountToBePaid || 0 }}</span>
              </div>
              <div class="contact">
                <span>结案时间：{{ item.closeCaseTime || '无' }}</span>
                <span style="margin-left: 20px">结案状态：{{ item.closeCaseStatus == 1 ? '未结案':'已结案' || '无' }}</span>
              </div>
            </div>
          </div>
        </van-list>
      </div>

      <!--<a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <a slot="purchaseNo" @click="inDepositoryOrderDetail(record)" slot-scope="text,record">{{ text }}</a>

        <span slot="action" slot-scope="text, record">
          <a @click="payment(record)" v-if="record.payStatus == 1 && record.amountToBePaid != 0 && record.closeCaseStatus == 1">付款</a>
          <a-divider type="vertical" v-if="record.payStatus == 1 && record.amountToBePaid != 0 && record.closeCaseStatus == 1"/>
          <a @click="closeCase(record)" v-if="record.closeCaseStatus == 1">结案</a>
          <a @click="noCloseCase(record)" v-if="record.closeCaseStatus == 2">反结案</a>
        </span>

      </a-table>-->
    </div>

    <van-popup v-model="showSearchPopupFlag" position="top" >
      <a-card :bordered="false">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <div>开工时间：
            <a-input @click="receiptsDate.show = true" v-model="receiptsDate.text" readOnly style="text-align: center;"></a-input>
            <van-popup v-model="receiptsDate.show" round position="bottom">
              <van-picker
                show-toolbar
                title="请选择时间"
                :columns="receiptsDateList"
                value-key="itemText"
                @cancel="receiptsDate.show = false"
                @confirm="changeReceiptsDate" />
            </van-popup>
          </div>
          <div style="margin-top: 5px">结案时间：
            <a-input @click="closeCaseDate.show = true" v-model="closeCaseDate.text" readOnly style="text-align: center;"></a-input>
            <van-popup v-model="closeCaseDate.show" round position="bottom">
              <van-picker
                show-toolbar
                title="请选择时间"
                :columns="closeCaseDateList"
                value-key="itemText"
                @cancel="closeCaseDate.show = false"
                @confirm="changeCloseCaseDate" />
            </van-popup>
          </div>
          <div style="margin-top: 5px">供应商：
            <van-dropdown-menu>
              <van-dropdown-item v-model="currentSupplier" :options="supplierData" @change="changeSupplier"/>
            </van-dropdown-menu>
          </div>

          <!--<div>客户姓名：<a-input placeholder="请输入客户姓名" v-model="queryParam.name"></a-input></div>
          <div style="margin-top: 5px">电话：<a-input placeholder="请输入客户电话" v-model="queryParam.phone"></a-input></div>
          <div style="margin-top: 5px">项目地址：<a-input placeholder="请输入项目地址" v-model="queryParam.address"></a-input></div>
          <div style="margin-top: 5px">当前进展：
            <van-dropdown-menu>
              <van-dropdown-item v-model="value1" :options="progressOption" @change="changeProgress"/>
            </van-dropdown-menu>
          </div>-->
          <a-row :gutter="24" style="margin-bottom: 10px;margin-top: 10px">
            <a-col :span="12">
              <a-button type="primary" style="width: 100%" @click="searchQuery" icon="search">查询</a-button>
            </a-col>
            <a-col :span="12">
              <a-button type="primary" @click="searchReset" icon="reload" style="width: 100%">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
    </van-popup>

    <in-depository-order-detail-modal ref="inDepositoryOrderDetailModal"></in-depository-order-detail-modal>
    <pending-payment-modal ref="pendingPaymentModal" @ok="modalFormOk"></pending-payment-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { filterObj } from '@/utils/util';
  import {mixinDevice} from '@/utils/mixin'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import {getAction,putAction} from "../../../../api/manage";
  import inDepositoryOrderDetailModal
    from "../../supplychain/purchaseInDepositoryOrder/modules/inDepositoryOrderDetailModal";
  import pendingPaymentModal from "./modules/pendingPaymentModal";

  export default {
    name: 'purchasePendingPaymentList',
    mixins: [JeecgListMixin, mixinDevice],
    components: {
      inDepositoryOrderDetailModal,pendingPaymentModal,
    },
    data() {
      return {
        description: '财务管理采购待付款页面',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '订单编号',
            align: "center",
            dataIndex: 'purchaseNo',
            slots: { title: 'customTitle' },
            scopedSlots: { customRender: 'purchaseNo' },
          },
          {
            title: '单据日期',
            align: "center",
            dataIndex: 'createTime'
          },
          {
            title: '供应商',
            align: "center",
            dataIndex: 'supplierName'
          },
          {
            title: '采购人员',
            align: "center",
            dataIndex: 'purchasePeople'
          },
          {
            title: '仓库',
            align: "center",
            dataIndex: 'depositoryName'
          },
          {
            title: '创建人',
            align: "center",
            dataIndex: 'createBy'
          },
          {
            title: '应付金额',
            align: "center",
            dataIndex: 'sumPayable',
            customRender:function (text) {
              if (text != null){
                return text+"元"
              }else {
                return "-"
              }
            }
          },
          {
            title: '已付金额',
            align: "center",
            dataIndex: 'amountPaid',
            customRender:function (text) {
              if (text != null && text != 0){
                return text+"元"
              }
              return "";
            }
          },
          {
            title: '待付金额',
            align: "center",
            dataIndex: 'amountToBePaid',
            customRender:function (text) {
              if (text != null){
                return text+"元"
              }else {
                return "-"
              }
            }
          },
          {
            title: '结案状态',
            align: "center",
            dataIndex: 'closeCaseStatus',
            customRender:function (text) {
              switch (text) {
                case 1:
                  return "未结案"
                  break;
                case 2:
                  return "已结案"
                  break;
              }
            }
          },
          {
            title: '结案时间',
            align: "center",
            dataIndex: 'closeCaseTime',
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            fixed: "right",
            width: 147,
            scopedSlots: {customRender: 'action'}
          }
        ],
        /* 数据源 */
        dataSource:[],
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        url: {
          list: "/ghSupplychainPurchaseOrder/purchasePendingPaymentList",
          deleteBatch: "/ghSupplychainPurchaseOrder/deleteBatch",
          exportXlsUrl: "/ghSupplychainPurchaseOrder/exportXls",
          importExcelUrl: "/ghSupplychainPurchaseOrder/importExcel",
          edit: "/ghSupplychainPurchaseOrder/edit",
          getSearchConditionData: "/ghSupplychainPurchaseOrder/getQueryCriteriaData",

          querySupplierList: "/ghSupplychainSupplier/allList",
          queryUserList: "/erp/user/selectUserByDepartId",
          queryDepartTreeList: "/erp/user/selectDepartTreeList",
          editCloseCase: "/ghSupplychainPurchaseOrder/editCloseCase"
        },
        model:{},
        currentSupplier:'',
        supplierData: [{text:'全部',value:''}],   //供应商列表
        purchasePeopleData:[],  //采购人员列表
        createByData:[],    //创建人列表
        currentReceiptsType: 0,
        currentReceiptsDate: '',
        currentCloseCaseDate: '',
        currentOrderStatus: 0,
        receiptsDateList:[],  //搜索条件：单据时间
        closeCaseDateList:[], //搜索条件：结案时间
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        dataFields: {
          title: 'departName',
          key: 'id',
          value: 'id',
          children: "children"
        },
        currentDepartId: "",  //当前所选部门
        departListData:[],    //部门列表
        finished: false,
        showSearchPopupFlag: false,
        receiptsDate:{
          show:false,
          text:'全部',
        },
        closeCaseDate:{
          show:false,
          text:'全部',
        },
      }
    },
    created() {
      this.initSearchConditionData();
      this.loadDepartTreeListData();
      this.loadSupplierData();
      //this.loadData();
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      showSearchPopup(){
        this.showSearchPopupFlag = true
      },
      //加载用户列表
      loadUserListData() {
        getAction(this.url.queryUserList,{departId:this.currentDepartId}).then((res) => {
          if (res.success) {
            this.purchasePeopleData = res.result.records||res.result;
            this.createByData = res.result.records||res.result;
          }
        })
      },
      //加载供应商
      loadSupplierData(){
        //this.supplierData = []
        getAction(this.url.querySupplierList).then((res) => {
          if (res.success) {
            let supplierData = res.result.records||res.result;
            for (let i=0;i<supplierData.length;i++){
              supplierData[i].text = supplierData[i].supplierName
              supplierData[i].value = supplierData[i].supplierName
            }
            this.supplierData = [...this.supplierData,...supplierData];
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      changeSupplier(value){
        this.showSearchPopupFlag = false
        this.queryParam.supplierName = value
        this.loadData(1);
      },
      changePurchasePeople(value){
        this.loadData(1);
      },
      changeCreateBy(value){
        this.loadData(1);
      },
      changeCloseCaseStatus(value){
        this.loadData(1);
      },
      filterOptionSupplier(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      filterOptionPurchasePeople(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      filterOptionCreateBy(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      initSearchConditionData() {
        getAction(this.url.getSearchConditionData).then(res => {
          if (res.success) {
            this.receiptsDateList = res.result.receiptsDateList;
            this.closeCaseDateList = res.result.closeCaseDateList;
          }
        })
      },

      //付款
      payment(record){
        this.$refs.pendingPaymentModal.title = "新增付款单";
        this.$refs.pendingPaymentModal.add(record);
      },

      //结案
      closeCase(record){
        var that = this;
        let params = {};
        params.id = record.id;
        params.closeCaseStatus = 2;
        if (record.amountToBePaid != 0){
          this.$confirm({
            title: "信息",
            content: "温馨提示：该订单还有未付款金额，是否确定结案？",
            onOk: function () {
              putAction(that.url.editCloseCase,params).then((res) => {
                if (res.success) {
                  that.$message.success("反结案成功");
                  that.loadData();
                } else {
                  that.$message.warning(res.message);
                }
              })
            }
          });
        }else {
          putAction(this.url.editCloseCase,params).then((res =>{
            if (res.success){
              that.$message.success("结案成功");
              that.loadData();
            }else {
              that.$message.warning(res.message);
            }
          }))
        }
      },
      //反结案
      noCloseCase(record){
        var that = this;
        this.$confirm({
          title: "信息",
          content: "温馨提示：是否确定反结案？",
          onOk: function () {
            let params = {};
            params.id = record.id;
            params.closeCaseStatus = 1;
            putAction(that.url.editCloseCase,params).then((res) => {
              if (res.success) {
                that.$message.success("反结案成功");
                that.loadData();
              } else {
                that.$message.warning(res.message);
              }
            })
          }
        });
      },
      //详情
      inDepositoryOrderDetail(record){
        this.$refs.inDepositoryOrderDetailModal.title = "采购入库订单详情";
        this.$refs.inDepositoryOrderDetailModal.showDetail(record);
      },
      modalFormOk(){
        this.loadData();
      },
      onLoadList(e){
        this.ipagination.current++
        this.loadData(this.ipagination.current)
      },
      loadData(arg) {
        if(!this.url.list){
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
          this.dataSource = []
          this.finished = false;
        }
        var params = this.getQueryParams();//查询条件

        if (this.currentReceiptsDate != null && this.currentReceiptsDate != '') {
          params.currentReceiptsDate = this.currentReceiptsDate;
          if (this.currentReceiptsDate == "customizeTime"){
            params.beginTime = this.startDate1;
            params.endTime = this.endDate1;
          }
        }else {
          params.currentReceiptsDate = "";
        }

        if (this.currentCloseCaseDate != null && this.currentCloseCaseDate != '') {
          params.currentCloseCaseDate = this.currentCloseCaseDate;
          if (this.currentCloseCaseDate == "customizeTime"){
            params.beginTime2 = this.startDate2;
            params.endTime2 = this.endDate2;
          }
        }else {
          params.currentCloseCaseDate = "";
        }

        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = [...this.dataSource, ...res.result.records]
            if(res.result.total)
            {
              this.ipagination.total = res.result.total;
            }else{
              this.ipagination.total = 0;
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }else{
            this.$message.warning(res.message)
          }
          if(res.result.records.length<10){
            this.finished = true;
          }
        }).finally(() => {
          this.loading = false
        })
      },
      //加载部门树形列表
      loadDepartTreeListData(){
        getAction(this.url.queryDepartTreeList).then((res) => {
          if (res.success) {
            this.departListData = res.result.records||res.result;
          }
        })
      },
      changeDepart(value){
        this.currentDepartId = value;
        this.loadUserListData();
      },
      changeReceiptsDate(e){
        this.receiptsDate.text = e.itemText
        this.receiptsDate.show = false
        const { key, itemValue, itemText } = e
        this.currentReceiptsDate = itemValue
        let obj = {
          key,
          itemValue,
          itemText
        }
        this.loadData(1)
        this.showSearchPopupFlag = false
      },
      changeCloseCaseDate(e){
        this.closeCaseDate.text = e.itemText
        this.closeCaseDate.show = false
        const { key, itemValue, itemText } = e
        this.currentCloseCaseDate = itemValue
        let obj = {
          key,
          itemValue,
          itemText
        }
        this.loadData(1)
        this.showSearchPopupFlag = false
      },
      searchQuery(){
        this.loadData(1);
        this.selectedRowKeys = []
        this.selectedRows = []
        this.showSearchPopupFlag = false
      },
      searchReset() {
        this.currentSupplier = ""
        this.currentReceiptsDate = ""
        this.currentCloseCaseDate = ""
        this.receiptsDate.text = "全部"
        this.closeCaseDate.text = "全部"
        this.queryParam = {}
        this.selectedRowKeys = []
        this.selectedRows = []
        this.showSearchPopupFlag = false
        this.loadData(1);
      },
    }
  }
</script>

<style scoped>
  @import '~@assets/less/common.less';

  /deep/ .van-dropdown-menu__bar{
    height: 30px;
    box-shadow: none;
    border: 1px solid lightgrey;
    border-radius: 5px;
  }

  .list{
    overflow-y: scroll;
    height:100vh;
  }
  ::-webkit-scrollbar {
    display: none;
  }
  .customer-list {
    align-items: center;
    border-top: 1px solid #d9d9d9;
    /*height: 120px;*/
  }
  .name{
    margin-top: 10px;
    margin-bottom: 5px;
    font-size: 13px;
    color: #161616;
    line-height: normal;
  }
  .contact{
    font-size: 12px;
    color: #a39f9f;
    margin-bottom: 5px;
  }
</style>